package com.hud.easynavi;

import java.util.Formatter;

/**
 * CAN 数据解析
 * Created by lucian on 17-3-13.
 */

public class CanDataParser
{
    static CanDataParser instance = new CanDataParser();

    public static CanDataParser getInstance(){
        return instance;
    }

    public interface Listener{
        void onCanMsgSignal(int can_id,boolean valid,String signal,float value_f,int value_i);
    }

    Listener listener;

    public void setListener(Listener ls){
        listener = ls;
    }

    public  void parse(int can_id,byte[] frame_data)
    {
        boolean valid;
        switch (can_id){
            case CAN_ID.car_speed: // 车速 km/h
                logData("speed",can_id,frame_data);
                valid = (frame_data[0] & (0x01<<7)) == 0 ;
                float car_speed = ((frame_data[0]&0x7F)<<8 | (frame_data[1] & 0xFF)) * 0.015625f;
                notifyParseResult(can_id,valid,"车速",car_speed,-1);
                break;
            case CAN_ID.gear_level:// 档位 0x0~0x0F
                logData("gear_level",can_id,frame_data);
                valid = (frame_data[3] & (0x01 << 4)) == 0;
                int gear_level = frame_data[3] & 0x0F;
                notifyParseResult(can_id,valid,"档位",0f,gear_level);
                break;
            case CAN_ID.remain_distance: //剩余里程 km
                logData("remain_distance",can_id,frame_data);
                valid = true;
                int mileage_rest = (frame_data[6] & 0x0F) << 8 | frame_data[7]&0xFF;
                notifyParseResult(can_id,valid,"剩余里程",0f,mileage_rest);
                break;
            case CAN_ID.remain_battery_power: // 剩余电量 百分比 0~102.3%
                logData("remain_battery",can_id,frame_data);
                valid = (frame_data[4] & (0x01 << 6 )) == 0;
                float percent = ((frame_data[2] & 0x03 ) << 8 | frame_data[3]&0xFF) * 0.1f;
                notifyParseResult(can_id,valid,"剩余电量",percent,-1);
                break;
            default:
                break;
        }
    }

    void notifyParseResult(int can_id,boolean valid,String signal,float vf,int vi){
        if(listener!=null){
            listener.onCanMsgSignal(can_id,valid,signal,vf,vi);
        }
    }

    void logData(String tag,int can_id,byte[] can_frame)
    {
        Formatter formatter = new Formatter();
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<8;i++)
        {
            sb.append(formatter.format("%02X ", can_frame[i] & 0xFF));
        }
        sb.toString();
        System.out.println(tag+" CANID:"+Integer.toHexString(can_id)+" FRAME:"+sb.toString() + "\n");
    }
}
